package com.jingfu.Service.impl;

import com.jingfu.Service.DeptmentService;
import com.jingfu.common.BadRequestException;
import com.jingfu.common.ErrorCode;
import com.jingfu.dto.TreeDTO;
import com.jingfu.dto.UserDeptDTO;
import com.jingfu.mapper.SysDeptMapper;
import com.jingfu.mapper.SysUserMapper;
import com.jingfu.pojo.SysDept;
import com.jingfu.pojo.SysUser;
import com.jingfu.pojo.SysUserRole;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author jingfuu@163.com
 * @version v1.0
 * @date 2022/2/8 下午3:32
 **/
@Service
@Slf4j
public class DeptmentServiceImpl implements DeptmentService {
    @Autowired
    SysDeptMapper sysDeptMapper;

    @Autowired
    SysUserMapper sysUserMapper;

    @Override
    public List<TreeDTO> getDeptmentTree() {
        List<SysDept> sysDepts = sysDeptMapper.findAll();
        return doGetDeptmentTree(sysDepts);
    }

    @Override
    public void deleteUserDept(String userId) {
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(userId);
        if (Objects.isNull(sysUser)) {
            throw new BadRequestException(ErrorCode.PARAM_IS_ERROR);
        }
        sysUser.setDeptId(null);
        sysUserMapper.updateUserDeptByPrimaryKey(sysUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchCreateUserDept(UserDeptDTO userDeptDTO) {
        SysDept sysDept = sysDeptMapper.selectByPrimaryKey(userDeptDTO.getDeptId());
        if (Objects.isNull(sysDept)) {
            throw new BadRequestException(ErrorCode.PARAM_IS_ERROR);
        }
        userDeptDTO.getUserIds().forEach(userId->{
            SysUser sysUser = new SysUser();
            sysUser.setUserId(userId);
            sysUser.setDeptId(userDeptDTO.getDeptId());
            sysUserMapper.updateUserDeptByPrimaryKey(sysUser);
        });

    }

    private List<TreeDTO> doGetDeptmentTree(List<SysDept> sysDepts) {
        List<TreeDTO> treeDTOS = sysDepts.stream().map(sysDept -> {
            TreeDTO treeDTO = new TreeDTO();
            treeDTO.setTitle(sysDept.getDeptName());
            treeDTO.setId(sysDept.getDeptId());
            treeDTO.setParentId(sysDept.getParentId());
            treeDTO.setSort(sysDept.getSort());
            return treeDTO;
        }).collect(Collectors.toList());
        List<TreeDTO> firstLevelTree = treeDTOS.stream()
                .sorted(Comparator.comparing(TreeDTO::getSort))
                .filter(treeDTO -> "0".equals(treeDTO.getParentId())).collect(Collectors.toList());

        List<TreeDTO> otherLevelTree = treeDTOS.stream()
                .filter(treeDTO -> !"0".equals(treeDTO.getParentId())).collect(Collectors.toList());
        //递归整理树形数据
        doHandlerTree(firstLevelTree,otherLevelTree);
        return firstLevelTree;
    }

    private void doHandlerTree(List<TreeDTO> firstLevelTree, List<TreeDTO> otherLevelTree) {
        firstLevelTree.forEach(treeDTO -> {
            Iterator<TreeDTO> iterator = otherLevelTree.iterator();
            while (iterator.hasNext()) {
                TreeDTO next = iterator.next();
                if (next.getParentId().equals(treeDTO.getId())) {
                    treeDTO.getChildren().add(next);
                    iterator.remove();
                }
            }
        });
        if (otherLevelTree.isEmpty()){
            return;
        }
        firstLevelTree.stream().filter(treeDTO -> !treeDTO.getChildren().isEmpty()).forEach(treeDTO -> {
            List<TreeDTO> collect = treeDTO.getChildren().stream()
                    .sorted(Comparator.comparing(TreeDTO::getSort))
                    .collect(Collectors.toList());
            treeDTO.setChildren(collect);
            doHandlerTree(treeDTO.getChildren(), otherLevelTree);
        });
    }
}
